﻿using Kingdee.BOS;
using Kingdee.BOS.App.Data;
using Kingdee.BOS.Contracts;
using Kingdee.BOS.Core.Report;
using Kingdee.BOS.Util;
using Kingdee.K3.FIN.CB.App.Report;
using System.ComponentModel;
using System.Linq;

namespace LM.CB.K3Cloud.Plugin
{
    [Description("自产产品实际成本报表（从完工入库成本查询扩展）"), HotUpdate]
    public class StockInCostDetailRptPlus : StockInCostDetailRpt
    {
        public override ReportHeader GetReportHeaders(IRptParams filter)
        {
            var headers = base.GetReportHeaders(filter);
            headers.AddChild("标准成本", new LocaleValue("标准成本", Context.UserLocale.LCID));
            return headers;
        }

        public override void BuilderReportSqlAndTempTable(IRptParams filter, string tableName)
        {
            var dbService = ServiceFactory.GetDBService(Context);
            var tempTableNames = dbService.CreateTemporaryTableName(Context, 1);
            var tempTableName = tempTableNames.Last();
            TempTableNameList.Add(tempTableName);
            // 将标准报表的数据存入指定表
            base.BuilderReportSqlAndTempTable(filter, tempTableName);

            var customerFilters = filter.FilterParameter.CustomFilter;
            var year = customerFilters["Year"]?.ToString() ?? "0";
            var period = customerFilters["Period"]?.ToString() ?? "0";
            var endYear = customerFilters["FEndYear"]?.ToString() ?? "0";
            var endPeriod = customerFilters["FEndPeriod"]?.ToString() ?? "0";
            var startDate = year + period.PadLeft(2, '0');
            var endDate = endYear + endPeriod.PadLeft(2, '0');

            // 从过渡表中取数到扩展表
            var sql = $@"/*dialect*/select a.*, b.F_RDLV_PRODUCTAMT as '标准成本'
                into {tableName}
                from {tempTableName} as a
                left join (
                    select F_RDLV_PRODUCTID, F_RDLV_ORGID
                        , F_RDLV_PRODUCTAMT-- 产品金额
                    from RDLV_t_BugCostTree
                    where FID in (
	                    select max(FID)
	                    from RDLV_t_BugCostTree-- 预算成本树形查询
	                    -- 将年月拼接成数值，然后进行筛选
	                    where cast((cast(F_RDLV_YEAR as varchar) + right('0' + cast(F_RDLV_MONTH as varchar), 2)) as int) between {startDate} and {endDate}
	                    -- 按产品、组织分组
	                    group by F_RDLV_PRODUCTID, F_RDLV_ORGID
                    )
                ) b on b.F_RDLV_PRODUCTID = a.FMaterialField and b.F_RDLV_ORGID = a.FCargoOwnerId";
            DBUtils.Execute(Context, sql);
            //var d = DBUtils.ExecuteDynamicObject(Context, $"select top 5 * from {tableName}");
            //var j = JsonUtil.Serialize(d);
            //throw new KDBusinessException(null, j);
        }
    }
}
